package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {


    @Autowired
    private AddressMapper addressMapper;
    // 查询收货地址列表
    @Override
    public List<Address> findList() {
        // 1.构建条件  select * from address_book where user_id = ?
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId());

        // 2.查询并返回
        return addressMapper.selectList(qw);
    }

    //新增收货地址

    @Override
    public void add(Address address) {
        //补全信息
        address.setUserId(UserHolder.get().getId());//用户id
        address.setIsDefault(0);//设置默认地址
        //调用mapper新增
         addressMapper.insert(address);
    }
//回显地址
    @Override
    public Address findById(Long id) {
       return addressMapper.selectById(id);

    }
//修改地址
    @Override
    public void updateAdress(Address address) {
        //构建条件
        addressMapper.updateById(address);

    }

    //设置默认地址
    @Override
    public void setDefault(Long id) {
        //将当前用户所有的默认地址为0 ，update address_book set is_fefault =0 wnere user_id =?
        //准备修改内容
        Address address1 = new Address();//set is_default =0
        address1.setIsDefault(0);
        //1-2构建修改条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();//where user-ID=?
        qw.eq(Address::getUserId, UserHolder.get().getId());
        //1-3更新数据库
        addressMapper.update(address1, qw);
        //2. 将当前前端传递地址id设置为默认收货地址  update address_bookset isdefault=1 where id？
        Address address2 = new Address();
        address2.setIsDefault(1);
        address2.setId(id);
        addressMapper.updateById(address2);
    }
    // 查询默认收货地址
    @Override
    public Address findDefault() {
        //1.根据用户的id+ 默认状态查询 selevt * from address_book where user_id=? and is_default =1
        LambdaQueryWrapper<Address> add = new LambdaQueryWrapper<>();
        add.eq(Address::getUserId, UserHolder.get().getId()); // user_id = ?
        add.eq(Address::getIsDefault, 1);// is_default = 1
        //调用mapper查询
        return addressMapper.selectOne(add);
    }


}
